<script>
import MAIN_STORE from "@/store/store.js";
import { CloseBold, Location, Download, Switch, Sort } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus'
import { MeasureClearDistance } from "@/utils/Measure";
import mitt from "mitt";
import { ref, reactive } from "vue";
import SelfDraggable from '@/components/Draggable/Draggable.vue';
import Api from '@/Api'
// 
let mittBus = null;



function getListData(data) {
  const filtersAttr = ['pointion']
  const keys = Object.keys(data || {}).filter(v => {
    return filtersAttr.indexOf(v) === -1;
  })
  const listData = keys.map(v => { return { key: v, value: data[v] } })
  return listData
}
export default {
  /**
   * 净距分析
   */
  name: "decision-distance",
  components: { CloseBold, Location, SelfDraggable, Download, Switch, Sort },
  data() {
    return {
      dialogDrawer: false,
      // 表单
      realForm: {
        radius: 50,
        type: 'point'
      },
      // 是否正在绘制
      isPainting: false,
      // 是否有查询的数据
      dataForPaintVER: [],
      dataForPaintHOR: [],
      bufferForm: {
        "drawPoints": {
          "coordinates": [],
          "crs": { "type": "MultiLineString", "properties": { "name": "EPSG:4326" } }
        }
      },
      // 选中的项 id
      selectedId: null,
      listData: [],
      emptyText: '暂无数据',
      colorOfLine: 'rgba(19, 206, 102, 0.8)',
      mainTitle: '净距分析',
      currentType: ''
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    mainTitle_() {
      if (!this.currentType) { return '' }
      return {
        VER: '[垂直分析]',
        HOR: '[水平分析]'
      }[this.currentType]
    }
  },
  watch: {
    visible: function (nV) {
      if (!nV) {
        const ins = MeasureClearDistance.getIns();
        ins && ins.destroy();
        this.dataForPaintVER = [];
        this.dataForPaintHOR = [];
        this.selectedId = null;
      }
    }
  },
  mounted() {
  },
  beforeUnmount() {
    mittBus && mittBus.all.clear();
    mittBus = null;
    const ins = MeasureClearDistance.getIns();
    ins && ins.destroy();
    this.dataForPaintVER = [];
    this.dataForPaintHOR = [];
    this.selectedId = null;
  },
  methods: {
    // 开始选中点
    selectPoint(type) {
      this.dataForPaintVER = [];
      this.dataForPaintHOR = [];
      // this.bufferForm.polygon = null;
      // 如果正在绘制
      this.currentType = type;
      if (this.isPainting) {
        // 结束绘制
        this.isPainting = false;
        // 销毁绘制实例
        const ins = MeasureClearDistance.getIns();
        ins && ins.destroy();
      } else {
        // 开始绘制
        this.isPainting = true;
        // 生成绘制实例
        let ins = MeasureClearDistance.getIns();
        if (!ins) {
          mittBus = mitt();
          ins = MeasureClearDistance.create({
            map: MAIN_STORE.GLOBAL_MAP_INS,
            overlayLimit: (type && type === 'VER') ? 1 : 2,
            mittBus: mittBus,
            type
          });
          ins.mittBus.on('VER', ({ data }) => {
            this.doQuery({ type: 'VER', data: data[0] })
          })

          ins.mittBus.on('HOR', ({ data }) => {
            this.doQuery({ type: 'HOR', data: data })
          })

        }
      }
    },
    // 数据查询
    async doQuery({ type, data }) {
      // if (!this.bufferForm.polygon) { return }
      let url = '';
      let bufferForm = {};
      if (type === 'VER') {
        url = 'iobject/pipe_analyse/freeDistance-vertical';
        bufferForm = {
          "BH": data.bh || data.BH,
          "GXXZ": data.gxxz || data.GXXZ,
        }
      } else if (type === 'HOR') {
        url = 'iobject/pipe_analyse/freeDistance-horizontal';
        bufferForm = {
          "lineA": {
            "BH": data[0].bh || data[0].BH,
            "GXXZ": data[0].gxxz || data[0].GXXZ,
          },
          "lineB": [
            {
              "BH": data[1].bh || data[1].BH,
              "GXXZ": data[1].gxxz || data[1].GXXZ,
            }
          ]
        }
      }
      if (!url) { return }
      this.selectedId = null;
      this.dataForPaintVER = []
      this.dataForPaintHOR = []
      this.emptyText = '正在分析...'
      const res = await Api.getAnaliseNormal({
        url: url,
        data: bufferForm
      })
      if (type === 'VER') {
        if (res.succ || res.success) {
          this.dataForPaintVER = res.data;
          const r = [];
          if (this.dataForPaintVER) {
            this.dataForPaintVER.forEach(v => {
              if (v.crossPoint) {
                v.crossPoint.value = Number(v['垂直净距'] || 0).toFixed(2)
                r.push(v.crossPoint);
              }
            })
          }
          const ins = MeasureClearDistance.getIns();
          if (ins) {
            ins.setCrossPointLine({ data: r, isOnlyPoint: true });
          }
        } else {
          ElMessage({
            message: res.msg || res.message,
            type: 'warning',
          })
          this.dataForPaintVER = []
          const ins = MeasureClearDistance.getIns();
          if (ins) {
            ins.clearCrossPointLine();
          }
        }
      }
      if (type === 'HOR') {
        if (res.succ || res.success) {
          this.dataForPaintHOR = res.data;
          if (this.dataForPaintHOR) {
            this.dataForPaintHOR.forEach(v => {
              v.distance = v.distance.toFixed(2)
            })
            const ins = MeasureClearDistance.getIns();
            if (ins) {
              ins.setCrossPointLine({ data: this.dataForPaintHOR, isOnlyPoint: false });
            }
          }
        } else {
          ElMessage({
            message: res.msg || res.message,
            type: 'warning',
          })
          this.dataForPaintHOR = []
          const ins = MeasureClearDistance.getIns();
          if (ins) {
            ins.clearCrossPointLine();
          }
        }
      }
      this.emptyText = '暂无数据'
    },
    close() {
      this.isPainting = false;
      this.$emit('close')
    },
    getDetail(data, scope) {
      const ins = MeasureClearDistance.getIns();
      if (!ins) { return }
      this.listData = getListData(data)
      this.dialogDrawer = true;
      this.getPos(data, scope, this.listData)
    },
    // 定位
    getPos(data, scope, listData) {
      this.selectedId = scope.$index;
      const coordinates = [data.pointion.x, data.pointion.y];
      this.$store.commit("LOCATION_CERTAIN_VIEW", {
        position: coordinates,
        accu: true
      });
      const ins = MeasureClearDistance.getIns();
      if (!ins) { return }
      // 设置用于定位的 overlay
      // ins.setOverlayForLocate({
      //   coordinate: coordinates,
      //   listData: listData || getListData(data)
      // });
    },
    getPosHOR(data, scope) {
      this.getPos({
        pointion: JSON.parse(JSON.stringify(data))
      }, scope, [])
    },
    closeDrawer() {
      this.dialogDrawer = false;
    },
    download() {
      this.$store.commit('DOWNLOAD_EXCELL_DATA', {
        data: this.dataForPaintVER,
        title: dayjs().format('YYYY-MM-DD')
      })
    },
    normalize(value) {
      if (!value) return ''
      return (Number(value)).toFixed(2)
    }
  },
};
</script>

<template>
  <div class="search-buffer">
    <div class="header">
      <span>
        {{ mainTitle }}
        <small>
          {{ mainTitle_ }}
        </small>
      </span>
      <div class="function-area">
        <div v-if="dataForPaintVER.length || dataForPaintHOR.length" class="icon-area hover-pointer" @click="download">
          <Download></Download>
        </div>
        <div class="icon-area hover-pointer" @click="close">
          <CloseBold></CloseBold>
        </div>
      </div>

    </div>
    <el-form size="small" inline :model="realForm" label-width="40px">
      <el-form-item>
        <el-button v-if="isPainting" text size="small" type="primary" @click="selectPoint">
          取消
        </el-button>
        <el-button v-if="!isPainting" text size="small" type="primary" @click="selectPoint('VER')">
          <el-icon>
            <Sort />
          </el-icon>垂直分析
        </el-button>
        <el-button v-if="!isPainting" text size="small" type="primary" @click="selectPoint('HOR')">
          <el-icon>
            <Switch />
          </el-icon>水平分析
        </el-button>
      </el-form-item>
    </el-form>
    <div v-if="currentType === 'VER'">
      <el-table :data="dataForPaintVER" stripe style="width: 100%" max-height="250">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="上面管类" label="上面管类" width="120" />
        <el-table-column prop="下面管类" label="下面管类" width="120" />
        <el-table-column prop="上管管径" label="上管管径" width="120" />
        <el-table-column prop="下管管径" label="下管管径" width="120" />
        <el-table-column prop="国家规范" label="国家规范" width="100" />
        <el-table-column prop="垂直净距" label="垂直净距" width="100">
          <template #default="scope">
            {{ normalize(scope.row['垂直净距']) }}
          </template>
        </el-table-column>
        <el-table-column prop="是否规范" label="是否规范" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button link :type="selectedId === scope.$index ? 'success' : 'primary'" size="small"
              @click="getDetail(scope.row, scope)">详情</el-button>
            <!-- <el-button link :type="selectedId === scope.$index ? 'success' : 'primary'" size="small"
              @click="getPos(scope.row, scope)">
              定位
            </el-button> -->
          </template>
        </el-table-column>
        <template #empty>
          <el-tag type="info">
            {{ emptyText }}
          </el-tag>
        </template>
      </el-table>
    </div>
    <div v-if="currentType === 'HOR'">
      <el-table :data="dataForPaintHOR" stripe style="width: 100%" max-height="250">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="水平净距" label="水平净距(米)" width="auto">
          <template #default="scope">
            {{ normalize(scope.row['distance']) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <!-- <el-button link :type="selectedId === scope.$index ? 'success' : 'primary'" size="small"
              @click="getDetail(scope.row, scope)">详情</el-button> -->
            <el-button link :type="selectedId === scope.$index ? 'success' : 'primary'" size="small"
              @click="getPosHOR(scope.row.pointA, scope)">
              定位A
            </el-button>
            <el-button link :type="selectedId === scope.$index ? 'success' : 'primary'" size="small"
              @click="getPosHOR(scope.row.pointB, scope)">
              定位B
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-tag type="info">
            {{ emptyText }}
          </el-tag>
        </template>
      </el-table>
    </div>
    <el-drawer v-model="dialogDrawer" title="详细信息" :before-close="closeDrawer" direction="rtl" class="demo-drawer">
      <div class="demo-drawer__content">
        <el-descriptions :column="2" title="" border>
          <el-descriptions-item v-for="(item, index) in listData" :key="index" :label="item.key">{{ item.value
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>
<style></style>
<style lang="less" scoped>
:deep(.demo-drawer .el-drawer__body) {
  --el-drawer-padding-primary: 0;
}

:deep(.demo-drawer .el-drawer__header) {
  margin-bottom: 20px;
}

.search-buffer {
  &>.header {
    font-size: 16px;
    color: #2168b2;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &>.function-area {
      display: inline-flex;

      &>.icon-area {
        width: 20px;
        height: 20px;
      }
    }
  }
}
</style>
